<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/3/8 0008
 * Time: 21:01
 */

namespace Home\Action;


class AppServerAction extends BaseAction{


    /**
     * 发送短信
     * @param $code
     * @param $phone
     * @return mixed
     */
    public function  sendSMS($code,$phone){
        return WSTSendSMS($phone,$code);
    }

    /**
     * 修改密码
     * userId,
     * newPwd，
     * code,
     * uniuqId
     *
     *
     */
    public function changePassword(){

        $result["status"] = 0;
        $code = M("Code")->field("code,createTime")->where(array("uniuqId"=>I("post.uniuqId")))->find();
        if(time() > strtotime('+5 min',intval($code["createTime"]))){
            $result["msg"] = "验证码超时";

        }else if($code["code"] != I("post.code")){
            $result["msg"] = "验证码无效";
        }else{
            $userId = I("post.userId");
            $data['userId'] = $userId;
            $rs = M("users")->field("loginPwd,loginSecret")->where(array("userId"=>$userId))->find();

            $newPwd = md5(I("post.newPwd").$rs["loginSecret"]);
            if($newPwd == $rs["loginPwd"]){
                $result["msg"] = "新密码不能和旧密码一样";
                $this->ajaxReturn($result);
            }
            M("users")->save(array("userId"=>$userId,"loginPwd"=>$newPwd));
            $result["msg"] = "修改成功";
            $result["status"] = 1;
        }


        $this->ajaxReturn($result);
    }


    /**
     * 重置密码
     *
     * userId
     * userPwd
     * newPwd
     */
    public function resetPassword(){
        $userId = I("post.userId");
        $user = M("users")->field("loginPwd,loginSecret")->where(array("userId"=>$userId))->find();
        $userPwd =  md5(I("post.userPwd").$user["loginSecret"]);
        $data["status"] = 0;
        if($user["loginPwd"] != $userPwd){
            $data["msg"] = "密码错误";
            $this->ajaxReturn($data);
        }

        $newPwd = md5(I("post.newPwd").$user["loginSecret"]);
        M("users")->save(array("userId"=>$userId,"loginPwd"=>$newPwd));
        $data["msg"] = "修改成功";
        $data["status"] = 1;
        $this->ajaxReturn($data);
    }

    /**
     * 用途：获取短信验证码
     * 传参方式  get
     * @param $phone     手机号码
     * 输出格式：json
     * 输出结构  {status:0/1}    0代表短信发送失败
     */
    public function getPhoneCheckCode(){

        $phone = I("post.phone");
        $result["status"] = 0;
        $length = 4;
        $code = rand(pow(10,($length-1)), pow(10,$length)-1);
        if($this->sendSms($code,$phone)){
            $checkCode['code'] = $code;
            $checkCode['createTime'] = time();
            $checkCode["uniuqId"] = uniqid();
            M("Code")->add($checkCode);
            $result["status"] = 1;
            $result["uniuqId"] = $checkCode["uniuqId"];
        }
        $this->ajaxReturn($result);

    }


    /**\
     *用户登录
     * loginName
     * loginPwd
     */
    public function loginUser(){
        $rv = array('status'=>0);
        $loginName = I('post.loginName');
        $userPwd = I('post.loginPwd');

        $sql ="SELECT * FROM __PREFIX__users WHERE (loginName='".$loginName."' OR userEmail='".$loginName."' OR userPhone='".$loginName."') AND userFlag=1 and userStatus=1 ";

        $rss = M()->query($sql);



        if(!empty($rss)){
            $rs = $rss[0];
            if($rs['loginPwd']!=md5($userPwd.$rs['loginSecret'])){
                $rv["msg"] = "密码错误";
                $this->ajaxReturn($rv);
            }

            if($rs['userFlag'] == 1 && $rs['userStatus']==1){

                $data = array();
                $data['lastTime'] = date('Y-m-d H:i:s');
                $data['lastIP'] = get_client_ip();
                M("Users")->where(" userId=".$rs['userId'])->data($data)->save();

                //记录登录日志
                $data = array();
                $data["userId"] = $rs['userId'];
                $data["loginTime"] = date('Y-m-d H:i:s');
                $data["loginIp"] = get_client_ip();
                M('log_user_logins')->add($data);
                unset($rs['loginSecret']);
                unset($rs['loginPwd']);
                unset($rs['payPwd']);
                $rv = $rs;
                $v["shopInfo"] = array();
                if($rs["belongToShopId"]){
                    $shopInfo = M("Shops")->where(array("shopId"=>$rs["belongToShopId"]))->find();
                    $rv["shopInfo"] = $shopInfo;

                }else if($rs["userType"]==1){
                    $shopInfo = M("Shops")->where(array("userId"=>$rs['userId']))->find();
                    $rv["shopInfo"] = $shopInfo;
                }

                $rv["status"] = 1;
                $rv["msg"] = "登录成功";
            }else{
                $rv["msg"] = "请联系管理员启用该用户";

            }
        }else{
            $rv["msg"] = "该用户不存在";
        }
        $this->ajaxReturn($rv);

    }


    /**
     * 更新用户信息
     * userName
     * userSex
     * userPhoto
     * userId
     */

    public function updateUserInfo(){
        $utils = new \Think\HYUtils();
        $userPhoto = $utils->uploadimg("Upload/users/", $_FILES["userPhoto"]);
        if($userPhoto == 'empty' || $userPhoto == 'toobig' || $userPhoto == 'errortype' || $userPhoto == 'moveerror')$userPhoto = null;

        $data["status"] = 0;
        $data['msg'] = "更新失败";
        $m = M("Users");
        if($m->create()){
            if($userPhoto != null){
                $m->userPhoto = $userPhoto;
            }
            if($m->save()){
                $data["status"] = 1;
                $data['msg'] = "更新成功";
                $userId = I("post.userId");
                $data["userInfo"] = $m->where(array("userId"=>$userId))->find();
            }
        }
        $this->ajaxReturn($data);
    }


    /**
     * 消费记录
     * userId
     * pageNo
     * pageSize
     */

    function getPurchaseRecord(){
        $userId = I("post.userId");
        $pageNo = I("post.pageNo")-1;
        $pageSize = I("post.pageSize");
        $sql = <<<EOT
SELECT
	a.*, b.payName,
	CONCAT(MONTH(a.createTime),"月") AS m,
	CONCAT(YEAR (a.createTime),"年") AS y
FROM
	wst_log_moneys a
LEFT JOIN wst_payments b ON a.payType = b.id
WHERE
	a.targetId = $userId
ORDER BY
	createTime DESC
LIMIT $pageNo*$pageSize,
 $pageSize
EOT;

        $prList = M()->query($sql);
        $res = array();
        foreach($prList as $v){
            $res[$v['y']][$v['m']][] = $v;
        }

        array_multisort($res,SORT_DESC);

        $this->ajaxReturn($res);


    }



    /**
     * 获取支付方式列表
     */

    public function getPaymentList(){
        $result = M("Payments")->where(array("enabled"=>1))->order("payOrder")->select();
        $this->ajaxReturn($result);
    }


    /**
     * 获取银行列表
     */
    public function getBankList(){
        $this->ajaxReturn(D("Banks")->queryByList());
    }


    /**
     * 绑定银行卡/支付宝
     * userId
     * accTargetId   银行绑定的话需要，为银行列表中某银行Id
     * accNo      账号
     * accUser    绑定人
     * accType    1/3  支付宝/银行卡
     */
    public  function bindBankCart(){

        $m = M("CashConfigs");
        $data["status"] = 0;
        $accType = I("post.accType",3);
        if(!(M("users")->where(array("userId"=>I("post.userId")))->find())){
            $data["msg"] = "用户不存在";
            $this->ajaxReturn($data);
        }

        if($m->where(array("accNo"=>I("post.accNo")))->find()){
            $data["msg"] = "该支付账号已存在";
            $this->ajaxReturn($data);
        }

        if($accType == 3 ){
            $m->accTargetId = I("post.accTargetId");
        }
        $m->userId = I("post.userId");

        $m->accNo = I("post.accNo");
        $m->accUser = I("post.accUser");
        $m->accType = $accType;
        $m->areaId2 = 450600;
        $m->dataFlag = 1;
        $m->createTime = date("Y-m-d H:i:s");

        if($m->add()){
            $data["status"] = 1;
        }
        $this->ajaxReturn($data);
    }


    /**
     * 获取绑定支付宝或银行卡列表
     * userId
     */

    public function getBankCartList(){
        $userId = I("post.userId");
        $result = M("CashConfigs")->join("left join wst_banks on wst_cash_configs.accTargetId = wst_banks.bankId")->
        where(array("userId"=>$userId))->field("wst_cash_configs.* ,wst_banks.bankName")->select();
        $data = array();
        foreach($result as $v){

            $v["accType"] = intval($v["accType"]);
            if($v["accType"] == 3){
                $data[$v["accType"]][] = $v;
            }elseif($v["accType"] == 1){
                $data["zfb"] = $v;
            }

        }

        $this->ajaxReturn($data);

    }


    /**
     * 设置支付密码
     * payPwd
     * userPwd
     * userId
     */

    public function setPayPwd(){
        $rs["status"] = 0;
        $userId = I("post.userId");
        $userPwd = I("post.userPwd");
        $payPwd = I("post.payPwd");
        $m = M("users");
        $user = $m->where(array("userId"=>$userId))->field("loginPwd,loginSecret")->find();
        if( $user["loginPwd"]!=md5($userPwd.$user['loginSecret'])){
            $rs["msg"] = "密码错误";
            $this->ajaxReturn($rs);
        }

        $data["payPwd"]=md5($payPwd.$user["loginSecret"]);
        if($m->where(array("userId"=>$userId))->save($data)){
            $rs["status"]=1;
        }

        $this->ajaxReturn($rs);
    }



    /**
     * 商家资金提现
     * 支付密码  payPwd
     *  userId
     * configId  提现银行/支付宝账号
     * drawMoney  提现金额
     */


    public function shopDrawCash(){

        $userId = I("userId");
        $shopId = M("Shops")->where(array("userId"=>$userId))->getField("shopId");
        $rd = array('status'=>0);
        //验证支付密码
        $payPwd = I('post.payPwd');
        if(empty($payPwd)){
            $rd['msg'] = '请输入支付密码';
            $this->ajaxReturn($rd);
        }
        $sql = "select payPwd,loginSecret from __PREFIX__users where userId=".$userId;
        $user = M()->query($sql);
        if($user[0]['payPwd']!=md5(I("post.payPwd").$user[0]['loginSecret'])){
            $rd['msg'] = '支付密码不正确';
            $this->ajaxReturn($rd);
        }
        //获取提现账号信息
        if((int)I('configId')==0){
            $rd['msg'] = '请选择提现账号!';
            $this->ajaxReturn($rd);
        }
        $sql = "select l.*,b.bankName from __PREFIX__cash_configs l
		         left join __PREFIX__banks b on l.accTargetId=b.bankId
		         where l.dataFlag=1 and l.userId=".$userId." and l.id=".(int)I('post.configId');
        $config =  M()->query($sql);
        if(empty($config)){
            $rd['msg'] = '对不起,您的提现账号不存在!';
            $this->ajaxReturn($rd);
        }
        $money = (double)I('drawMoney');
        if($money<=0){
            $rd['msg'] = '提现金额必须大于0!';
            $this->ajaxReturn($rd);
        }
        //判断提现金额是否允许
        $sql = "select shopMoney from __PREFIX__shops where shopId=".$shopId;
        $shop = M()->query($sql);
        if($shop[0]['shopMoney']<$money){
            $rd['msg'] = '对不起，您的可提现金额不足!';
            $this->ajaxReturn($rd);
        }
        if($GLOBALS['CONFIG']['cashStartMoney']>$money){
            $rd['msg'] = '对不起，最低提现金额'.$GLOBALS['CONFIG']['cashStartMoney'].'元';
            $this->ajaxReturn($rd);
        }
        $cashModel = M("CashDraws");
        $cashModel->targetType = 1;
        $cashModel->targetId = $shopId;
        $cashModel->money = $money;
        $cashModel->accType = $config[0]['accType'];
        $cashModel->accTargetId = $config[0]['accTargetId'];
        $cashModel->accNo = $config[0]['accNo'];
        $cashModel->accUser = $config[0]['accUser'];
        $cashModel->cashSatus = 0;
        $cashModel->createTime = date('Y-m-d H:i:s');
        $cashModel->cashConfigId = (int)I('configId');
        $id =$cashModel->add();
        if(false !== $id){
            $data = array();
            $m = M('messages');
            $data["msgType"] = 0;
            $data["sendUserId"] = 0;
            $data["receiveUserId"] = $userId;
            $data["msgContent"] = "商家您申请提现 ¥".$money."已提交，预计明天24点前到帐！";
            $data["msgStatus"] = 0;
            $data["msgFlag"] = 1;
            $data["createTime"] = date('Y-m-d H:i:s');
            $m->add($data);
            $rd['status']= 1;
            $sql="update __PREFIX__shops set shopMoney=shopMoney-".$money.",lockMoney=lockMoney+".$money." where shopId=".$shopId;
            M()->execute($sql);
        }
        $this->ajaxReturn($rd);
    }


    /**
     * 养生服务员获取服务列表
     * shopId
     * serviceStatus  **** 服务状态  **** -1/0/1/2  ******全部/未接/已接/完成
     * pageSize
     * pageNo
     */

    public function getHealthService(){
        $pageNo = intval(I("post.pageNo")-1);
        $pageSize = intval(I("post.pageSize",10));
        $start = $pageSize*$pageNo;
        $shopId = I("post.shopId");

        $sql = <<<EOT
SELECT
	a.orderId, b.shopName,c.userName,c.userPhone,d.goodsName,d.goodsPrice,a.appointment,a.dropInAddress,a.serviceStatus
FROM
	wst_orders a
LEFT JOIN wst_shops b ON a.shopId like concat(",",b.shopId,",")
LEFT JOIN wst_users c on a.userId = c.userId
left join wst_order_goods d on a.orderId = d.orderId

WHERE
	a.shopId like "%,$shopId,%"
AND orderStatus = 2
EOT;


        $serviceStatus = I("post.serviceStatus");
        switch($serviceStatus){
            case -1:
                break;
            case 0:
                $sql .= " and serviceStatus = 0";
                break;
            case 1:
                $sql .= " and serviceStatus between 1 and 5";
                break;
            case 2:
                $sql .= " and serviceStatus = 6";
        }
        $sql .= " limit $start,$pageSize";

        $resultList = M()->query($sql);
        $this->ajaxReturn($resultList);

    }


    /**
     * ***养生商家服务员接/完成服务流程
     * ****waiterId   ***** 当前登录的服务员Id  既userId*****
     * ***lat      *****纬度      *****上门服务时需要******
     * ****lng        *****经度     *****上门服务需要*******
     * ***serviceStatus  **** 当前服务状态 **** 服务状态  2/3/4/5/6   ****出发/到达/开始服务/完成服务/返回  不用传
     */
    public function changeServiceStatus(){
        $data["status"] = 0;
        $data["msg"] = "操作失败";
        $waiterId = I("post.waiterId");
        $orderService = M("Orders")->where(array("waiterId"=>$waiterId,"serviceStatus"=>array('between','1,5')))->field("orderId,serviceStatus")->find();
        if($orderService){
            $m = M("HealthService");
            $serviceStatus = $orderService["serviceStatus"] + 1;
            $m->lat = I("post.lat",0);
            $m->lat = I("post.lng",0);
            $m->orderId = $orderService['orderId'];
            $m->statusTime = date("Y-m-d H:i:s");
            $m->serviceStatus = $serviceStatus;
            if($m->add()){
                if(M("Orders")->where(array("orderId"=> $orderService['orderId']))->setField("serviceStatus",$serviceStatus)){
                    $data["status"] = 1;
                    $data["serviceStatus"] = $serviceStatus;
                    $data["msg"] = "操作成功";
                }
            }


        } else{
            $data["msg"] = "未接到该服务或服务已完成";
        }

        $this->ajaxReturn($data);
    }

    /**
     * 服务员接单
     * waiterId  服务员Id
     * orderId   订单Id
     * type   0/1  上门/到店
     */
    public function takeService(){
        $data["status"] = 0;
        if(checkParameterEmpty(I("post."))){
            $data["msg"] = "参数不能为空";
            $this->ajaxReturn($data);
        }

        $data["msg"] = "接单错误";

        $m = M("Orders");
        $m->waiterId = I("post.waiterId");
        $m->serviceStatus = 1;
        if($m->where(array("orderId"=>I("post.orderId")))->save()){
            $data["status"] = 1;
            $data["msg"] = "接单成功";
        }

        $this->ajaxReturn($data);
    }


    /**
     * 获取服务会员某服务接单状态
     * ** waiterId***  服务员Id
     */

    public  function getWaiterServiceStatus(){
        $data["status"] = 0;

        $waiterId = I("post.waiterId");
        $orderId = M("Orders")->where(array("waiterId"=>$waiterId,"serviceStatus"=>array('between','1,5')))->getField("orderId");
        if($orderId){
            $statusList = M("HealthService")->where(array("orderId"=>$orderId))->select();
            if($statusList){
                $data["status"] = 1;
                $data["statusList"] = $statusList;
            }else{
                $data["msg"]="没有数据";
            }
        }else{
            $data["msg"] = "未接到该服务或服务已完成";
        }

        $this->ajaxReturn($data);
    }

    /**
     * 服务端确定退款
     * orderId
     * shopId
     * refundRemark
     */
    public function confirmRefund(){
        $data["status"] = 0;
        if(M("Orders")->where(array("orderId"=>I("post.orderId"),"shopId"=>I("post.shopId")))->
        save(array("isRefund"=>2,"refundRemark"=>I("post.refundRemark"),"orderStatus"=>3,"refundConfirmTime"=>date("Y-m-d H:i:s"),))){
            $data["status"] = 1;
        }

        $this->ajaxReturn($data);
    }

    /**
     * 投诉建议
     * userId
     * content
     */

    public function compliant(){
        $userId = I("post.userId");
        $content = I("post.content");
        $data["userId"] = $userId;
        $data["content"] = $content;
        $data["creatTime"] = time();
        $rs["status"] = 0;
        if( M("Complaint")->add($data)){
            $rs["status"] = 1;
        }

        $this->ajaxReturn($rs);

    }


    /**
     * 删除消息
     * userId
     * id
     */

    public function delSysMsg(){
        $id = I("post.id");
        $userId = I("post.userId");
        $data["status"] = 0;
        if(M("Messages")->where(array("receiveUserId"=>$userId,"id"=>$id))->delete()){
            $data["status"] = 1;
        }
        $this->ajaxReturn($data);
    }


    /**
     * 设置系统消息为已读
     * userId
     * id
     */
    public function ReadSysMsg(){
        $userId = I("post.userId");
        $id = I("post.id");
        $data["status"] = 0;
        if(M("Messages")->where(array("receiveUserId"=>$userId,"id"=>$id))->setField("msgStatus",1)){
            $data["status"] = 1;
        }
        $this->ajaxReturn($data);
    }

    /**
     * 获取系统消息
     * userId
     * pageNo
     * pageSize
     */
    public function getSysMsg(){
        $userId = I("post.userId");
        $pageNo = I("post.pageNo")-1;
        $pageSize = I("post.pageSize");
        $sql = "select * from wst_messages where receiveUserId = $userId ORDER BY msgStatus ,createTime desc limit $pageNo*$pageSize ,$pageSize";
        $msgList = M()->query($sql);
        $this->ajaxReturn($msgList);
    }






}